<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\adminapi\controller\translation;

use app\adminapi\controller\Base;
use app\common\model\ContentTranslation;
use app\common\model\TranslationJob;
use app\common\model\Language;
use app\service\translation\ContentTranslationService;

/**
 * 翻译管理控制器
 */
class Translation extends Base
{
    /**
     * @notes 获取翻译列表
     * @auth true
     */
    public function getList()
    {
        $page         = inputs('page/d', 1);
        $limit        = inputs('limit/d', 20);
        $tableName    = inputs('table_name/s', '');
        $languageCode = inputs('language_code/s', '');
        $status       = inputs('status/d', -1);

        $where = [];
        if ($tableName) {
            $where[] = ['table_name', '=', $tableName];
        }
        if ($languageCode) {
            $where[] = ['language_code', '=', $languageCode];
        }
        if ($status >= 0) {
            $where[] = ['translation_status', '=', $status];
        }

        $list = ContentTranslation::where($where)
            ->with(['language'])
            ->order('created_at', 'desc')
            ->paginate([
                'list_rows' => $limit,
                'page'      => $page,
            ]);

        $this->success('', $list);
    }

    /**
     * @notes 获取翻译详情
     * @auth true
     */
    public function getDetail()
    {
        $id          = inputs('id/d', 0);
        $translation = ContentTranslation::with(['language'])->find($id);

        if (!$translation) {
            $this->error('翻译记录不存在');
        }

        $this->success('', $translation);
    }

    /**
     * @notes 更新翻译内容
     * @auth true
     */
    public function updateTranslation()
    {
        $id                = inputs('id/d', 0);
        $translatedContent = inputs('translated_content/s', '');

        $translation = ContentTranslation::find($id);
        if (!$translation) {
            $this->error('翻译记录不存在');
        }

        $translation->translated_content = $translatedContent;
        $translation->translation_status = 1;
        $translation->is_reviewed        = 1;
        $translation->save();

        $this->success('翻译更新成功');
    }

    /**
     * @notes 批量审核翻译
     * @auth true
     */
    public function batchReview()
    {
        $ids    = inputs('ids/a', []);
        $action = inputs('action/s', 'approve'); // approve, reject

        if (empty($ids)) {
            $this->error('请选择要操作的翻译');
        }

        $status = $action === 'approve' ? 1 : 2;
        $count  = ContentTranslation::whereIn('id', $ids)->update([
            'translation_status' => $status,
            'is_reviewed'        => 1
        ]);

        $this->success("批量{$action}成功，共处理{$count}条记录");
    }

    /**
     * @notes 删除翻译
     * @auth true
     */
    public function deleteTranslation()
    {
        $id          = inputs('id/d', 0);
        $translation = ContentTranslation::find($id);

        if (!$translation) {
            $this->error('翻译记录不存在');
        }

        $translation->delete();
        $this->success('删除成功');
    }

    /**
     * @notes 重新翻译
     * @auth true
     */
    public function retranslate()
    {
        $tableName       = inputs('table_name/s', '');
        $recordId        = inputs('record_id/d', 0);
        $fieldName       = inputs('field_name/s', '');
        $targetLanguages = inputs('target_languages/a', []);

        if (!$tableName || !$recordId || !$fieldName) {
            $this->error('参数不完整');
        }

        $translationService = new ContentTranslationService();
        $job                = $translationService->createTranslationJob($tableName, $recordId, $fieldName, $targetLanguages);

        if ($job) {
            $this->success('翻译任务创建成功');
        } else {
            $this->error('翻译任务创建失败');
        }
    }

    /**
     * @notes 获取翻译统计
     * @auth true
     */
    public function getStats()
    {
        $translationService = new ContentTranslationService();
        $stats              = $translationService->getTranslationStats();

        // 添加按表分组的统计
        $tableStats    = ContentTranslation::getStatsByTable();
        $languageStats = ContentTranslation::getStatsByLanguage();

        $stats['by_table']    = $tableStats;
        $stats['by_language'] = $languageStats;

        $this->success('', $stats);
    }

    /**
     * @notes 获取可翻译的表列表
     * @auth true
     */
    public function getTranslatableTables()
    {
        $tables = \app\common\model\TranslationConfig::getTranslatableTables();
        $this->success('', $tables);
    }

    /**
     * @notes 批量处理翻译任务
     * @auth true
     */
    public function processJobs()
    {
        $limit = inputs('limit/d', 10);

        $translationService = new ContentTranslationService();
        $processed          = $translationService->batchProcessJobs($limit);

        $this->success("成功处理{$processed}个翻译任务");
    }

    /**
     * @notes 清理翻译数据
     * @auth true
     */
    public function cleanupTranslations()
    {
        $days = inputs('days/d', 7);
        $type = inputs('type/s', 'failed'); // failed, completed

        if ($type === 'failed') {
            $count = ContentTranslation::cleanFailedTranslations($days);
            $this->success("清理了{$count}条失败的翻译记录");
        } else {
            $count = TranslationJob::cleanCompletedJobs($days);
            $this->success("清理了{$count}条已完成的翻译任务");
        }
    }

    /**
     * @notes 导出翻译数据
     * @auth true
     */
    public function exportTranslations()
    {
        $tableName    = inputs('table_name/s', '');
        $languageCode = inputs('language_code/s', '');

        $where = [];
        if ($tableName) {
            $where[] = ['table_name', '=', $tableName];
        }
        if ($languageCode) {
            $where[] = ['language_code', '=', $languageCode];
        }

        $translations = ContentTranslation::where($where)
            ->where('translation_status', 1)
            ->select()
            ->toArray();

        $this->success('', $translations);
    }
}
